package com.tongshu.miaosha.controller;

import com.tongshu.miaosha.domain.MiaoshaUser;
import com.tongshu.miaosha.redis.GoodsKey;
import com.tongshu.miaosha.result.Result;
import com.tongshu.miaosha.service.GoodsService;
import com.tongshu.miaosha.utils.RedisUtil;
import com.tongshu.miaosha.vo.GoodsDetailVo;
import com.tongshu.miaosha.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    // Thymeleaf提供的页面解析器，用于渲染html，已自动注入
    private ThymeleafViewResolver thymeleafViewResolver;

    @RequestMapping(value = "/to_list", produces = "text/html")
    @ResponseBody
    public String list(HttpServletRequest request,
                       HttpServletResponse response,
                       Model model, MiaoshaUser user) {
        // 1.取缓存
        String  html = (String) redisUtil.get(GoodsKey.getGoodsList, "");
        if (!StringUtils.isEmpty(html))
            return html;

        model.addAttribute("user", user);

//        if (user == null)
//            return "login";

        // 查询商品列表并显示
        List<GoodsVo> goodsVos = goodsService.listGoodsVo();
        model.addAttribute("goodsList", goodsVos);

        // 2. 手动渲染并缓存
        IWebContext ctx = new WebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
        if (!StringUtils.isEmpty(html)) {
            redisUtil.set(GoodsKey.getGoodsList, "", html);
        }
        return html;
    }

    @RequestMapping(value = "/to_detail/{goodsId}", produces = "text/html")
    @ResponseBody
    public String detail(HttpServletRequest request,
                         HttpServletResponse response,
                         Model model, MiaoshaUser user,
                         @PathVariable("goodsId") long goodsId) {
        // 1.取缓存
        String  html = (String) redisUtil.get(GoodsKey.getGoodsDetail, "" + goodsId);
        if (!StringUtils.isEmpty(html))
            return html;

        model.addAttribute("user", user);

        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);
        model.addAttribute("goods", goodsVo);

        long startAt = goodsVo.getStartDate().getTime();
        long endAt = goodsVo.getEndDate().getTime();
        long now = System.currentTimeMillis();

        int miaoshaStatus = 0; // 秒杀状态 开始 进行中 结束
        int remainSeconds = 0; // 秒杀倒计时
        if (now < startAt) { // 秒杀还没开始倒计时
            miaoshaStatus = 0;
            remainSeconds = (int) ((startAt - now) / 1000);
        } else if (now > endAt) { // 秒杀已经结束
            miaoshaStatus = 2;
            remainSeconds = -1;
        } else { // 秒杀进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("miaoshaStatus", miaoshaStatus);
        model.addAttribute("remainSeconds", remainSeconds);

        // 2. 手动渲染并缓存
        IWebContext ctx = new WebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);
        if (!StringUtils.isEmpty(html)) {
            redisUtil.set(GoodsKey.getGoodsDetail, "" + goodsId, html);
        }
        return html;

    }

    // 页面静态化
    @RequestMapping(value = "/detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVo> detail2(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Model model, MiaoshaUser user,
                                         @PathVariable("goodsId") long goodsId) {
        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);

        long startAt = goodsVo.getStartDate().getTime();
        long endAt = goodsVo.getEndDate().getTime();
        long now = System.currentTimeMillis();

        int miaoshaStatus = 0; // 秒杀状态 开始 进行中 结束
        int remainSeconds = 0; // 秒杀倒计时
        if (now < startAt) { // 秒杀还没开始倒计时
            miaoshaStatus = 0;
            remainSeconds = (int) ((startAt - now) / 1000);
        } else if (now > endAt) { // 秒杀已经结束
            miaoshaStatus = 2;
            remainSeconds = -1;
        } else { // 秒杀进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }

        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        goodsDetailVo.setGoods(goodsVo);
        goodsDetailVo.setMiaoshaStatus(miaoshaStatus);
        goodsDetailVo.setRemainSeconds(remainSeconds);
        goodsDetailVo.setUser(user);

        return Result.success(goodsDetailVo);
    }
}
